package com.macro.mall.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.macro.mall.bo.AdminUserDetails;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.ResultCode;
import com.macro.mall.common.api.SMSSend;
import com.macro.mall.common.api.SMSSendCode;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.common.utils.Assist;
import com.macro.mall.mapper.UmsMemberLogMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsMember;
import com.macro.mall.model.UmsMemberLog;
import com.macro.mall.security.service.RedisService;
import com.macro.mall.service.UmsMemberLogService;
import com.macro.mall.service.UmsMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * UmsMemberLog的服务接口的实现类
 *
 * @author gaodx
 */
@Slf4j
@Service
public class UmsMemberLogServiceImpl implements UmsMemberLogService {

    private boolean isDebugEnabled;

    @Autowired
    private UmsMemberLogMapper umsMemberLogMapper;
    @Autowired
    private UmsMemberService umsMemberService;
    @Autowired
    RedisService redisService;
    // TODO 当你看到这个方法时你应该创建一个工具类做通用的方法,定义自己的返回格式化

    @Override
    public List<UmsMemberLog> find(UmsMemberLog value) {
        //TODO这里可以做通过Assist做添加查询
        List<UmsMemberLog> result = null;
        try {
            result = umsMemberLogMapper.selectUmsMemberLog(null);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取UmsMemberLog数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public List<UmsMemberLog> find(String username, Integer pageNum, Integer pageSize) {
        //TODO这里可以做通过Assist做添加查询
        List<UmsMemberLog> result = null;
        PageHelper.startPage(pageNum, pageSize);
        Assist assist = new Assist();
        if (StrUtil.isNotEmpty(username)) {
            assist.andEq("phone", username);
        }
        PageHelper.orderBy("create_time desc");
        try {
            result = umsMemberLogMapper.selectUmsMemberLog(assist);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行获取UmsMemberLog数据集-->结果:", result);
        }
        return result;
    }

    @Override
    public UmsMemberLog findOne(Long id, String userName) {
        /*if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsMemberLog的id获得UmsMemberLog对象-->失败:id不能为空");
            }
            Asserts.fail("执行通过UmsMemberLog的id获得UmsMemberLog对象-->失败:id不能为空");
        }*/
        UmsMemberLog result = null;
        try {
            result = umsMemberLogMapper.selectUmsMemberLogById(id,userName);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsMemberLog的id获得UmsMemberLog对象-->结果:", result);
        }
        return result;
    }

    @Override
    public CommonResult saveNotNull(UmsMemberLog value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行将UmsMemberLog中属性值不为null的数据保存到数据库-->失败:对象不能为空");
            }
            Asserts.fail("失败:对象不能为空");
        }
        int result = 0;
        try {
//            SecurityContext ctx = SecurityContextHolder.getContext();
//            Authentication auth = ctx.getAuthentication();
//            AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
//            UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
//            Long adminId = umsAdmin.getId();
//            String adminName = umsAdmin.getUsername();

            result = umsMemberLogMapper.insertNotNullUmsMemberLog(value);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行将UmsMemberLog中属性值不为null的数据保存到数据库-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    @Transactional
    public CommonResult updateNotNullById(UmsMemberLog value) {
        if (value == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsMemberLog的id更新UmsMemberLog中属性不为null的数据-->失败:对象为null");
            }
            Asserts.fail("执行通过UmsMemberLog的id更新UmsMemberLog中属性不为null的数据-->失败:对象为null");
        }
        UmsMember umsMember = new UmsMember();
        UmsMemberLog one = new UmsMemberLog();
        int result = 0;
        try {

            one = umsMemberLogMapper.selectUmsMemberLogById(value.getId(),null);
            //01 -待审核 02 审核通过 03审核不通过
            if ("02".equals(value.getStatus())) {
                SecurityContext ctx = SecurityContextHolder.getContext();
                Authentication auth = ctx.getAuthentication();
                AdminUserDetails memberDetails = (AdminUserDetails) auth.getPrincipal();
                UmsAdmin umsAdmin = memberDetails.getUmsAdmin();
                Long id = umsAdmin.getId();
                String username = umsAdmin.getUsername();
                value.setOperationId(id+"");
                value.setOperationName(username);

                umsMember.setId(Long.parseLong(one.getUserId()));
                //umsMember.setUsername(one.getPhone());
                umsMember.setPhone(one.getPhone());
                umsMember.setName(one.getName());
                umsMember.setCommunityId(StringUtils.isEmpty(one.getCommunityId())?null:one.getCommunityId().intValue());
                umsMember.setCommunityName(one.getCommunityName());
                umsMember.setProvince(one.getProvince());
                umsMember.setCity(one.getCity());
                umsMember.setArea(one.getArea());
                umsMember.setIdCard(one.getIdCard());
                umsMember.setFloor(one.getFloor());
                umsMember.setStatus(1);
                umsMember.setUserIdentity(one.getUserIdentity());
                umsMemberService.updateUmsMemberSelective(umsMember);
                try {
                    SMSSend.sendSMS(one.getPhone(),
                            SMSSendCode.approved.getMasage().replaceAll("xcode",one.getPhone()),
                            SMSSendCode.approved.getCode());
                } catch (Exception e) {
                    log.error("短信发送失败",e);
                }
            } else if ("03".equals(value.getStatus())){
                try {
                    SMSSend.sendSMS(one.getPhone(),
                            SMSSendCode.failedexamine.getMasage().replaceAll("xcode",value.getReason()),
                            SMSSendCode.failedexamine.getCode());
                } catch (Exception e) {
                    log.error("短信发送失败",e);
                }
            }
            UmsMemberLog build = UmsMemberLog.builder().id(value.getId()).status(value.getStatus()).operationId(value.getOperationId()).operationName(value.getOperationName()).reason(value.getReason()).build();
            result = umsMemberLogMapper.updateNotNullUmsMemberLogById(build);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        } finally {
            redisService.del("mall:ums:member:" + one.getPhone());
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsMemberLog的id更新UmsMemberLog中属性不为null的数据-->结果:", result);
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult deleteById(Long id) {
        if (id == null) {
            if (isDebugEnabled) {
                log.debug("执行通过UmsMemberLog的id删除UmsMemberLog-->失败:id不能为空");
            }
            Asserts.fail("执行通过UmsMemberLog的id删除UmsMemberLog-->失败:id不能为空");
        }
        int result = 0;
        try {
            result = umsMemberLogMapper.deleteUmsMemberLogById(id);
        } catch (Exception e) {
            log.error("", e);
            Asserts.fail(ResultCode.FAILED);
        }
        if (isDebugEnabled) {
            log.debug("执行通过UmsMemberLog的id删除UmsMemberLog-->结果:", result);
        }
        return CommonResult.success(null);
    }


}